<%@page  import="merlin.beans.CustomerDetailsBean, merlin.managers.BibServiceManager, merlin.utils.ApplicationResources, java.util.Map" %>
<%

if(session.getAttribute("username") == null){
	response.sendRedirect("bibIndustryWatchLogin.jsp");
	return;
}

CustomerDetailsBean bean = (CustomerDetailsBean)session.getAttribute("userDetails");
int customerDetailsId = bean.getCustomerDetailsId();

String username = (String)session.getAttribute("username");
%>

<html>
	<head>
		<title>BIB Service Main Page</title>
		
		<link href="css/master.css" rel="stylesheet" type="text/css">
		
		<style>
			.textFont {font: 11px verdana,arial,sans-serif}
		</style>
		
		<!-- begin imports for creation of the tabs -->
		<link rel="stylesheet" type="text/css" href="mr_tabs/tabcontent.css" />
		<script type="text/javascript" src="mr_tabs/tabcontent.js">
		</script>
		<!-- ends imports for creation of the tabs -->
		
		<!-- begin DWR imports -->
		<script type='text/javascript' src='dwr/interface/BibServiceManager.js'></script>
		<script type='text/javascript' src='dwr/interface/MsalResearchersManager.js'></script>
		<script type='text/javascript' src='dwr/engine.js'></script>
		<script type='text/javascript' src='dwr/util.js'></script>
		<!-- ends DWR imports -->
		
		<!-- begin jQuery import -->
		<script type='text/javascript' src='mr_scripts/jquery.js'></script>
		<!-- ends jQuery import -->
		
		
		<!-- begin imports for Settings Menu -->
		<link rel="stylesheet" type="text/css" href="mr_menus/themes/office_xp/office_xp.css" />
		<script type="text/javascript" src="mr_menus/jsdomenubar.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.inc.bibService.js"></script>
		<!-- ends imports for Settings Menu -->
				
		<script>
			var customerDetailsId = <%=customerDetailsId%>

			jQuery.noConflict();
			
			// top menu scripts.
			function logOut(frm){
				document.location = 'bibIndustryWatchLogin.jsp';
			}
		</script>
		
		<script>
			// Tab 1 functions.			
			function searchReports(){
				var searchText = jQuery('#txtSearchReport').val();
				if(isBlank(searchText)){
					alert('Cannot leave the search field blank');
					return;
				}
				if(isSessionValid()){
					BibServiceManager.searchReports(searchText, handleSearchReports);
				}		
			}

			function handleSearchReports(result){
				jQuery('#lstReportTitles option').remove(); // remove all previous results.
				for(var i = 0; i < result.length; i++){
					jQuery('#lstReportTitles').append('<option value="' + result[i].reportTitlesId + '" noOfCompanies = "' + result[i].noOfCompaniesInDatabase + '">' + result[i].reportTitle + '</option>');							
				}
			}
						
			function moveRecords(lstFrom, lstTo){
				if(lstTo != null){
					jQuery('#' + lstFrom + ' :selected').each(function(){
						// duplicate check - if the element to be copied from lstFrom already exists in lstTo, skip it.
						var found = false; 
						var currentVal = jQuery(this).val();
						jQuery('#' + lstTo + ' option').each(function(){
							if(currentVal == jQuery(this).val()){
								found = true;
							}
						});
						if(!found){
							var opt = jQuery('<option></option').val(jQuery(this).val()).html(jQuery(this).text());
							opt.attr('noOfCompanies', jQuery(this).attr('noOfCompanies'));
							jQuery('#' + lstTo).append(opt);
						}
					});
					sortSelect(lstTo);
				}
				jQuery('#' + lstFrom + ' :selected').remove();
				
			}

			function downloadReports(){
				if(isSessionValid()){
					var reports = new Array();
	
					jQuery('#lstSelectedReports option').each(function(){
						reports.push({"reportTitlesId" : jQuery(this).val() , "reportTitle" : jQuery(this).text()});
					});

					if(reports.length > 0){
						BibServiceManager.sendReportDownloadEmail(reports, function(){alert("report download links sent via email.");});
					}
				}
			}

			function searchCompaniesByKeyword(){
				var strSearch = jQuery('#txtSearchCompany').val();
				if(isBlank(strSearch)){
					alert('Cannot leave the search field blank');
					return;
				}
				if(strSearch.length < 3){
					alert('Enter at least 3 characters in the search field');
					return;
				}

				if(isSessionValid()){
					jQuery('#txtSearchReport').val("");
					jQuery('#lstReportTitles option').remove();
					BibServiceManager.searchCompanies(strSearch, 
						jQuery('input[name=radSearchType]:checked').val() == 'alphakey', handleCompaniesSearchResult);
				}
			}

			function handleCompaniesSearchResult(result){
				jQuery('#lstCompanies option').remove(); // remove all previous results.
				for(var i = 0; i < result.length; i++){
					jQuery('#lstCompanies').append('<option value="' + result[i].companyNumber + '">' + result[i].companyName + '</option>');							
				}
				// select the first item in the result, and fire the event to retrieve its details.
				if(result.length > 0){
					jQuery('#lstCompanies option:first').attr('selected', 'selected');
					getCompanyDetails(result[0].companyNumber);
					getReportsByCompany();
				}
			}
			
			function getCompanyDetails(companyNumber){
				if(isSessionValid()){
					BibServiceManager.getCompanyDetails(companyNumber, handleCompanyDetailsResult);
				}
			}

			function handleCompanyDetailsResult(result){
				if(result != null){
					var companyDetails = result.companyDetails;
			    	var address = '';
					var s = companyDetails.addressLine1;
					if(s != null && s.length > 0)address += s + '<BR>';
					s = companyDetails.addressLine2;
					if(s != null && s.length > 0)address += s + '<BR>';
					s = companyDetails.town;
					if(s != null && s.length > 0)address += s + '<BR>';
					s = companyDetails.county;
					if(s != null && s.length > 0)address += s + '<BR>';
					s = companyDetails.postcode;
					if(s != null && s.length > 0)address += s;
					if(address.length == 0)address = '[No address found]';
					jQuery('#divAddress').html(address);
					
					s = companyDetails.businessDescription;
					if(s == null || s.length == 0){
						s ="[No description found]";
					}
					jQuery('#divBusinessDescription').html(s);

					// info about share holders
					var shareHolders = result.shareholderDetails;
					if(shareHolders != null && shareHolders.length > 0){
						// create the shareholder string
						var str = "<table border=1 cellspacing = 0 width='100%' style='FONT: 11px arial, verdana, sans-serif;'><thead><tr style='background-color:#A5CEFF;'><th >Shareholder</th><th style=''>Shareholdings</th></tr></thead><tbody class='overflow:auto'>";
						for(var i=0;i< shareHolders.length;i++){
			    			str += "<tr><td align='center' style=''>" + (shareHolders[i].shareholder!=null?shareHolders[i].shareholder:"&nbsp;") + "</td><td style='text-align:right'>" + (shareHolders[i].shareholding !=null?shareHolders[i].shareholding:"&nbsp;") + "</td></tr>";
						}
						str += "</tbody></table>";
						jQuery('#divShareholders').html(str);
					}else{
						jQuery('#divShareholders').html('[No shareholders found]');
					}
					
					// Info about the directors.
					jQuery('#lstDirectors option').remove();
					var directors = result.directorDetails;
					if(directors != null && directors.length > 0){
						for(var i=0;i< directors.length;i++){
					    	var directorVal = "";
							var sDir = directors[i].firstname;
							if(sDir != null)
								directorVal += sDir + '|';
							else
			                    directorVal += '|';
							sDir = directors[i].surname;
							if(s != null)
								directorVal += sDir + '|';
							else
			                    directorVal += '|';
							sDir = directors[i].dateOfBirth;
							if(sDir != null)
								directorVal += sDir;
							jQuery('#lstDirectors').append('<option value="' + directorVal + '">' + directors[i].director + '</option>');
						}
					}else{
						jQuery('#lstDirectors').append('<option value="-1">[No entries found]</option>');
					}

					//Info about the parent companies.
					var parentDetails = result.parentSubsidiaryDetails;
					if(parentDetails != null && parentDetails.length > 0){
						// create the parent string
						var sbSubsi = "<table border=1 cellspacing = 0 width='100%' style='FONT: 11px arial, verdana, sans-serif;'><thead><tr style='background-color:#A5CEFF;'><th>Company</th><th>Turnover</th></tr></thead><tbody class='overflow:auto'>";
						for(var i=0;i< parentDetails.length;i++){
			    			sbSubsi += "<tr>";
			    			if(parentDetails[i].subsidiaryRegistrationNumber.charAt(0) == '#'){
				    			// these are foreign companies with no details in the DB - grey them out, with no events attached.
			    				sbSubsi += "<td align='left'><span style='color:grey' >" + parentDetails[i].companyName + "</td>";
			    			}else{
								sbSubsi += "<td align='left'><a style='text-decoration:none;color:black' href='#' onclick='return searchCompanyByParent(\"" + parentDetails[i].subsidiaryRegistrationNumber + "\")'>" + parentDetails[i].companyName + "</a></td>";
			    			}
							sbSubsi += "<td style='text-align:right'>" + (parentDetails[i].turnover != null ? parentDetails[i].turnover :"&nbsp;") + "</td>";
							sbSubsi += "</tr>";
						}
						sbSubsi += "</tbody></table>";
						jQuery('#divSubsidiary').html(sbSubsi);
					}else{
						jQuery('#divSubsidiary').html("[No details found]");
					}

					// Info on the financial details.
					var financialDetails = result.financialDetails;
					if(financialDetails != null && financialDetails.length > 0){
						var sbFin = "<table border=1 cellspacing = 0 width='100%' style='FONT: 11px arial, verdana, sans-serif;'><thead><tr style='background-color:#A5CEFF;'><th>&nbsp;</th><th>Year 1</th><th>Year 2</th><th>Year 3</th><th>Year 4</th></tr></thead><tbody class='overflow:auto'>";
						for(var i=0;i< financialDetails.length;i++){
			    			sbFin += "<tr>";
							sbFin += "<td style='text-align:left'>" + financialDetails[i].description + "</td>";
							sbFin += "<td style='text-align:right'>" + (financialDetails[i].year1 !=null?financialDetails[i].year1:"&nbsp;") + "</td>";
							sbFin += "<td style='text-align:right'>" + (financialDetails[i].year2 !=null?financialDetails[i].year2:"&nbsp;") + "</td>";
							sbFin += "<td style='text-align:right'>" + (financialDetails[i].year3 !=null?financialDetails[i].year3:"&nbsp;") + "</td>";
							sbFin += "<td style='text-align:right'>" + (financialDetails[i].year4 !=null?financialDetails[i].year4:"&nbsp;") + "</td>";
							sbFin += "</tr>";

						}
						sbFin + "</tbody></table>";
						jQuery("#divSummaryFinancial").html(sbFin);
					}else{
						jQuery("#divSummaryFinancial").html("[No records found]");
					}
								
				} 
			}

			function getReportsByCompany(){
				// only if a single company is selected, then fetch the related reports.
				if(jQuery('#lstCompanies :selected').length == 1){
					if(isSessionValid()){
						jQuery('#txtSearchReport').val("");
						jQuery('#lstReportTitles option').remove();
						BibServiceManager.searchReportsByCompanyId(jQuery('#lstCompanies option:selected').val(),handleSearchReports);
					}
				}
			}
			
			function searchCompanyByDirector(strNumber){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}
				if(isSessionValid()){
					BibServiceManager.searchCompanyByDirector(strNumber, handleCompaniesSearchResult);
				}
			}

			function searchCompanyByParent(strNumber){
				if(isSessionValid()){
					BibServiceManager.searchCompanyByParent(strNumber, handleCompaniesSearchResult);
				}
				return false;
			}

			function generatePDF(companyId){
				if(companyId == null || companyId==""){
					alert("Please select a company from the search results list");
				}else{
					if(isSessionValid()){
						// open on a new window
						window.open("merlin?mode=createPDF&companyId=" + companyId,"pdf","height=600,width=600,resizable=yes,menubar=yes,scrollbars=yes,toolbar=no");
					}
   				}
			}
			
			function sendMailToAddCompaniesToReports(){
				if(isSessionValid()){
					var reports = new Array();
					var companies = new Array();
	
					jQuery('#lstSelectedReports option').each(function(){
						reports.push({"reportTitlesId" : jQuery(this).val() , "reportTitle" : jQuery(this).text()});
					});
	
					jQuery('#lstSelectedCompanies option').each(function(){
						companies.push({"companyNumber" : jQuery(this).val() , "companyName" : jQuery(this).text()});
					});
					if(companies.length > 0){
						BibServiceManager.sendMailToAddCompaniesToReports(reports, companies, function(){alert("email sent");});
					}
				}
			}

		</script>
		
		<script>
            //////// Scripts for the SWF-based Tab 2 implementation.//////////////////

            var savedCompaniesList;
            var customReports;
            
			// Function to get the pointer to the SWF.
			function getMyApp(appName) {
			    if (navigator.appName.indexOf ("Microsoft") !=-1) {
			        return window[appName];
			    } else {
			        return document[appName];
			    }
			}

			function tab2Opened(){
				setTimeout("MsalResearchersManager.getReportsList(handleGetReportNames)", 1500);
				if(savedCompaniesList != null){
					setTimeout('getMyApp("tab4").restoreSelectedCompaniesListForBIBService(savedCompaniesList)', 1500);
				}
				//saveCompanyListForBibService
			}

			function saveCompanyListForBibService(list){
				savedCompaniesList = list;
			}
			
			function saveCustomReportSWF(reportName,companies,selectedForReport){
				MsalResearchersManager.addCustomReport(reportName,customerDetailsId,companies,selectedForReport,handleAddCustomReportSWF);
			}

			function handleAddCustomReportSWF(data){
				try{
					getMyApp("tab4").customReportSavedCallback(data);
				}catch(e){
					// ignore.
				}
				createMenubar();
			}

			function getReportNamesSWF(){
				// no-op, reports will be added whenever the user clicks on the tab 2 header.
			}

			function handleGetReportNames(data){
				try{
					var reportChunkSize = <%=ApplicationResources.getInstance().getProperty("reportChunkSize")%>;
					
					// only select the previously saved custom reports.
					// defaultReport to open is either the first report selected in tab1, or the first custom report previously saved.
					if(data == null)data = new Array();
					customReports = new Array();
					var defaultReport = 0;
					if(data != null){
						for(var i=0;i<data.length;i++){
							if(data[i].customReport == true){
								if(defaultReport == 0)defaultReport = data[i].reportTitlesId;
								//customReports.push(data[i]);
								
								var noOfCompanies = parseInt(data[i].noOfCompaniesInDatabase); 

								if(noOfCompanies > reportChunkSize){
									// break the report into 'n' chunks
									var pages = Math.floor(noOfCompanies / reportChunkSize);
									if(noOfCompanies % reportChunkSize > 0)pages++;
									for(var p = 1;p <= pages;p++){
										customReports.push({"reportTitlesId" : data[i].reportTitlesId , "reportTitle" : data[i].reportTitle + " - Part " + p, "page" : p});
									}
								}else{
									customReports.push({"reportTitlesId" : data[i].reportTitlesId , "reportTitle" : data[i].reportTitle});
								}
							}
						}
					}
					// in addition to the user's saved reports, add those that he has selected in tab1.
					var firstReport = true;
					 
					jQuery('#lstSelectedReports option').each(function(){
						if(firstReport){
							defaultReport = jQuery(this).val();
							firstReport = false;
						}
						var noOfCompanies = parseInt(jQuery(this).attr('noOfCompanies')); 
						//alert(noOfCompanies + ':' + reportChunkSize);
						if(noOfCompanies > reportChunkSize){
							// break the report into 'n' chunks
							var pages = Math.floor(noOfCompanies / reportChunkSize);
							if(noOfCompanies % reportChunkSize > 0)pages++;
							for(var i = 1;i <= pages;i++){
								customReports.push({"reportTitlesId" : jQuery(this).val() , "reportTitle" : jQuery(this).text() + " - Part " + i, "page" : i});
							}
						}else{
							customReports.push({"reportTitlesId" : jQuery(this).val() , "reportTitle" : jQuery(this).text()});
						}
						
					});
					
					if(customReports.length == 0){
						alert("A report selection must be made before attempting to customise that selection.");
					}else{
						//getMyApp("tab4").reportListToAddForBIBService(customReports, defaultReport);
						setTimeout('getMyApp("tab4").reportListToAddForBIBService(customReports,' + defaultReport + ')', 1500);
					}
				}catch(e){
					alert("handleGetReportNames : " + e);
				}
			}
		</script>		
		
		
		<script>
			// tab 3 - Mailing List.
			
			function moveDirectorSectionRecord(lstFrom, lstTo, sortResults){
				if(lstTo != null){
					jQuery('#' + lstFrom + ' :selected').each(function(){
						jQuery('#' + lstTo).append(jQuery('<option></option').val(jQuery(this).val()).html(jQuery(this).text()));
					});
					if(sortResults)sortSelect(lstTo);
				}
				jQuery('#' + lstFrom + ' :selected').remove();
			}
			
			function exportMailingList(){
				if(savedCompaniesList == null || savedCompaniesList.length == 0){
					alert("No companies are chosen.");
					return; 
				}

				var addressType = jQuery('input[name=radDirectorAddressType]:checked').val();
				
				var directorTypes = new Array();
				jQuery('#lstSelectedDirectorSections option').each(function(){
					directorTypes.push(jQuery(this).val());
				});
				if(directorTypes.length == 0){
					alert('At least one director type must be selected');
					return;
				}

				// send mailing list.
				if(isSessionValid()){
					var companyIds = new Array();
					for(var i=0;i<savedCompaniesList.length;i++){
						companyIds.push(savedCompaniesList[i].cId);
					}
					var reportNames = "";
					for(var i=0;i<customReports.length -1;i++){
						reportNames += customReports[i].reportTitle + ", ";
					}
					reportNames += customReports[customReports.length - 1].reportTitle;
					BibServiceManager.generateMailingList(companyIds, addressType, directorTypes, reportNames, function(){alert('Mailing list generated');});
				}
			}
		</script>
		
		<script>
			// Scripts for the custom reports menus.
			function createMenubar(){
				MsalResearchersManager.getReportsList(handleReportNamesForMenubar);
			}

			function handleReportNamesForMenubar(data){
				customReports = new Array();
				if(data != null){
					for(var i=0;i<data.length;i++){
						if(data[i].customReport == true){
							customReports.push(data[i]);
						}
					}
				}
				jQuery("#staticMenuBar").html("");
				initjsDOMenu(customReports);
			}

			function deleteCustomReport(reportId, reportName){
				if(confirm('Do you really want to delete the report ' + reportName)){
					MsalResearchersManager.deleteCustomReport(reportId, handleDeleteCustomReport);
				}
			}

			function handleDeleteCustomReport(data){
				handleReportNamesForMenubar(data);
				try{
					if(getMyApp("tab4").reportListToAddForBIBService){
						handleGetReportNames(data);
					}
				}catch(e){
					//ignore
				}
			}
			
			function downloadCustomReport(reportId, reportName){
				if(isSessionValid()){
					var reports = new Array();
					reports.push({"reportTitlesId" : reportId , "reportTitle" : reportName});
					BibServiceManager.sendReportDownloadEmail(reports, function(){alert("report download links sent via email.");});
				}
			}

			function renameCustomReport(reportId, reportName){
				var newReportName = prompt("New Report Name", reportName);
				if(newReportName != null && newReportName.length > 0){
					/*if(newReportName.indexOf('\'') > -1 || newReportName.indexOf('\"') > -1 ){
						alert("Error : Illegal characters in the report name.")
						return;
					}*/
					// same result handling as in delete custom report.
					MsalResearchersManager.renameCustomReport(reportId, newReportName, handleDeleteCustomReport); 
				}
			}
			
			function createCustomReportFromTab1Companies(){
				if(isSessionValid()){
					var companies = "";
					var selectedForReport = "";
					if(jQuery('#lstSelectedCompanies option').length > 0){
						jQuery('#lstSelectedCompanies option').each(function(){
							companies += "," + jQuery(this).val();
							selectedForReport += ",true";
						});
						companies = companies.substr(1);
						selectedForReport = selectedForReport.substr(1);
						var reportName = prompt("Report Name");
						if(reportName != null && reportName.length > 0){
							if(reportName.indexOf('\'') > -1 || reportName.indexOf('\"') > -1 ){
								alert("Error : Illegal characters in the report name.")
								return;
							}
							saveCustomReportSWF(reportName,companies,selectedForReport);
						}
					}
				}
			}

			function addToMailingListExclusionList(){
				if(isSessionValid()){
					var companies = new Array();
	
					if(jQuery('#lstSelectedCompanies option').length > 0){
						jQuery('#lstSelectedCompanies option').each(function(){
							companies.push(jQuery(this).val());
						});
						BibServiceManager.addToMailingListExclusionList(companies, function(){alert('Companies added.');});
					}
				}
			}

			function exportMailingListExclusionList(){
				if(isSessionValid()){
					BibServiceManager.exportMailingListExclusionList(function(){alert('Mail sent.');});
				}
			}

			function retrieveMailingListExclusionList(){
				if(isSessionValid()){
					BibServiceManager.retrieveMailingListExclusionList(
						function(result){
							jQuery('#lstSelectedCompanies option').remove(); // remove all previous results.
							for(var i = 0; i < result.length; i++){
								jQuery('#lstSelectedCompanies').append('<option value="' + result[i].companyNumber + '">' + result[i].companyName + '</option>');							
							}
						}
					);
				}				
			}

			function deleteMailingListExclusionList(){
				if(isSessionValid()){
					if(confirm('Are you sure you want to delete the entire mailing exclusion list ?')){
						BibServiceManager.deleteMailingListExclusionList(
							function(result){
								alert('Mailing Exclusion List deleted.');
							}
						);
					}
				}
			}
		</script>
		<script>
			// the session invalidation duration, in milliseconds
			var lastAccessedTime = new Date().getTime();

			// the session invalidation duration, in milliseconds
			var sessionDuration = <%= session.getMaxInactiveInterval()%> * 1000;

			var timerPointer = -1;
			var timerWarning = -1;

			/**
			* 	Function to check if the user is still having a valid session or has timed out.
			*	Adds two timeout functions to the windowd object -
			*		1. a function that shows a warning message to the user that his session is about to expire
			*			with an option to stay connected
			*		2. a automatic logout if the session times out.
			*/
			function isSessionValid(){
				var currentTime  = new Date().getTime();

				if((currentTime - lastAccessedTime) < sessionDuration){
					// session is valid.
					lastAccessedTime = currentTime;

					// cancel the existing timer(if any),and start again.
					if(timerPointer != - 1)clearTimeout(timerPointer);
					if(timerWarning != - 1)clearTimeout(timerWarning);

					timerPointer = setTimeout('logOut(document.frm)',sessionDuration);
					timerWarning = setTimeout('showLogoutWarning()',sessionDuration - 60000);

					return true;
				}else{
					// session has timed out, send to logout procedure.
					logOut(document.frm);
					return false;
				}
			}

			/**
			*  Shows the logout warning DIV.
			*/
			function showLogoutWarning(){
				document.getElementById("divStayLoggedIn").style.visibility = "visible";
			}

			/**
			* 	A function that provides the user the option to stay logged on 10 secs before the logout event.
			*/
			function stayLoggedOn(){
				if(isSessionValid()){
					document.getElementById("divStayLoggedIn").style.visibility = "hidden";
					MsalResearchersManager.stayConnected();
				}
			}
		</script>
		
		<script>
			// Utility functions
			function isBlank(str){
				var len = str.length;
				if(len==0)return true;	// zero-length string
				for(i=0;i<len;i++){
					if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
				}
				return true;
			}

		    // sort the select object in ascending order.
			function sortSelect(selectToSort) {
				try{
					// copy options into an array
				    var myOptions = new Array();
				    jQuery('#' + selectToSort + ' option').each(function(){
						myOptions.push({ optText:jQuery(this).text(), optValue:jQuery(this).val(), noOfCompanies : jQuery(this).attr('noOfCompanies')});
					});

					// sort array
					myOptions.sort(sortFuncAsc);

					// copy sorted options from array back to select box
					jQuery('#' + selectToSort + ' option').remove();


					for (var i=0; i < myOptions.length; i++) {
						jQuery('#' + selectToSort).append('<option value="' + myOptions[i].optValue + '" noOfCompanies = "' + myOptions[i].noOfCompanies + '">' + myOptions[i].optText + '</option>');							
					}
				}catch(e){
					alert("sortSelect : " + e.message);
				}
			}

        	// sort function - ascending (case-insensitive)
	        function sortFuncAsc(record1, record2) {
    	        var value1 = record1.optText.toLowerCase();
        	    var value2 = record2.optText.toLowerCase();
            	if (value1 > value2) return(1);
	            if (value1 < value2) return(-1);
    	        return(0);
        	}
		</script>
	</head>
	<body onload="isSessionValid();DWRUtil.useLoadingMessage();">
		<jsp:include page="mr_headerFreeUpdates.jsp"></jsp:include>

		<!-- DIV for displaying the option of staying logged in 10 seconds before the actual logoff -->
		<div align="center" id="divStayLoggedIn" style="color:black;background-color:#7823CD;visibility:hidden;position:absolute;left:280px;top:350px">
			<%= request.getHeader("user-agent").indexOf("MSIE") != -1 ? "<BR>" : "" %>
			<h3 style="padding: 2px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 15px;vertical-align:center;cursor:hand;" onclick="stayLoggedOn()">&nbsp; Click here to stay logged in to the Free Updates Service &nbsp;</h3>
		</div>

		<div align="center">
			<table width="750" align="center" cellpadding="0" cellspacing="0" border="0">
				<tr>
					<td>
						<br>
						<ul id="maintab" class="shadetabs">
							<li class="selected"><a href="#" rel="divFindReportsTab">&nbsp;&nbsp;&nbsp;Find Report&nbsp;&nbsp;&nbsp;</a></li>
							<li onclick="tab2Opened()"><a href="#" rel="divCustomizedReportTab">&nbsp;&nbsp;&nbsp;Customised Report&nbsp;&nbsp;&nbsp;</a></li>
							<li><a href="#" rel="divMailingListsTab">&nbsp;&nbsp;&nbsp;Mailing Lists&nbsp;&nbsp;&nbsp;</a></li>
						</ul>
						
						<!--  tab 1 starts -->
						<div id="divFindReportsTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
						
							<!--  Reports search begins -->
							<table cellspacing="0" cellpadding="1" style="width: 710px;MARGIN: 0px 0px 0px 9px;">
								<tr>
   									<td colspan="2" class="textFont"><b>To find reports of interest search by keyword in the title or description.</b></td>
 								</tr>
								<tr>
									<td colspan="2">
										<input type="text" id="txtSearchReport" style="TEXT-TRANSFORM: uppercase; WIDTH: 350px;" class="textFont"/> 
										<input name="btnSearch" type="button" class="input" value="Search For Report" style="font-size: 11px; width: 130px;" onclick="searchReports()"/>
									</td>
 								</tr>
								<tr class="textFont">
									<td style="width: 50%; padding:33px 0px 0px 0px;">The following Reports were found by this search.</td>
   									<td style="text-align:right;padding: 33px 0px 0px 0px;">The reports listed here are the titles you have selected.</td>
   								</tr>
   							</table>
   							<table cellspacing="0" cellpadding="1" style="width: 710px;font:11px verdana,arial, sans-serif;MARGIN: 0px 0px 0px 9px;">
   								<tr class="textFont">
									<td style="WIDTH: 260px">
										<SELECT id="lstReportTitles" MULTIPLE style="width: 250px;height:65px;" class="textFont">
										</SELECT>
									</td>
									<td style="text-align:center">
										<input type="button" value="Add Report &gt;" style="font-size: 11px; width: 130px;" onclick="moveRecords('lstReportTitles','lstSelectedReports')"/>
										<input type="button" value="&lt; Remove Report" style="font-size: 11px; width: 130px;" onclick="moveRecords('lstSelectedReports','lstReportTitles')"/>
										<input type="button" value="Download Report" style="font-size: 11px; width: 130px;" onclick="downloadReports()"/>
									</td>
									<td style="WIDTH: 260px; TEXT-ALIGN: right">
										<SELECT id="lstSelectedReports" MULTIPLE style="width: 250px;height:65px;" class="textFont">
										</SELECT>
									</td>
								</tr>
							</table>
							<!--  Reports search ends -->
							<p/>							
							<!--  Company search begins -->
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 720px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="WIDTH: 33%" class="textFont">
										<b>Search for <input type="radio" name="radSearchType" value="alphakey" checked>Alphakey or <input type="radio" name="radSearchType" value="keyword"> Keyword (Name, Keyword, Director, Registration Number or Address).</b>
									</td>
								</tr>
								<tr>
									<td>
										<input id="txtSearchCompany" style="TEXT-TRANSFORM: uppercase; WIDTH: 350px;FONT: 11px arial, verdana, sans-serif;"  >
										<input type="button" style="FONT-SIZE: 11px; WIDTH: 130px" value="Search For Firm  >" onclick="searchCompaniesByKeyword()">
									&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button"  name="btnPrintPDF" style="FONT-SIZE: 11px; WIDTH: 95px" value="Print PDF" onclick="generatePDF(jQuery('#lstCompanies option:selected').val())">
									</td>
								</tr>
							</table>
						
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="WIDTH: 260px">
										<span class="textFont">The following companies were found by this search(click to view a company of interest)</span>
										<SELECT id="lstCompanies" size="4" MULTIPLE style="WIDTH: 250px;height:65px;" class="textFont" onchange="getCompanyDetails(this.value);getReportsByCompany()">
										</SELECT>
									</td>
									<td style="TEXT-ALIGN: center">
										<br/>
										<input type="button" name="btnAddCompany" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="moveRecords('lstCompanies','lstSelectedCompanies')">
										<input type="button" name="btnRemoveCompany" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="moveRecords('lstSelectedCompanies',null)">
										<input type="button" name="btnUpdate" value="Send FREE Update" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="sendMailToAddCompaniesToReports()">
									</td>
									<td style="WIDTH: 260px; TEXT-ALIGN: right">
										<span id="spnSelectedCompanies" class="textFont">Companies to include in your new report<br>(click to delete a company)</span>
										<SELECT id="lstSelectedCompanies" size="4" MULTIPLE style="WIDTH: 250px;height:65px;" class="textFont">
										</SELECT>
									</td>
								</tr>
							</table>

							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="0" cellspacing="0">
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 250px"><strong>Address</strong></td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Shareholders</strong></td>
								</tr>
								<tr>
									<td>
										<DIV id="divAddress" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto; HEIGHT:70px; WIDTH: 240px; FONT: 11px arial, verdana, sans-serif;"></DIV>
									</td>
									<td>
										<DIV id="divShareholders" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px; FONT: 11px arial, verdana, sans-serif;" ></DIV>
									</td>
								</tr>
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Directors &amp; Company Secretary</strong></td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Ultimate Parent(UP), Parent(P), Subsidiaries Undertakings(S)</strong></td>
								</tr>
								<tr>
									<td>
										<SELECT id="lstDirectors" style="MARGIN: 0px 10px 0px 0px;HEIGHT:72px; WIDTH: 240px;FONT: 11px arial, verdana, sans-serif;" MULTIPLE onchange="searchCompanyByDirector(this.value)"></SELECT>
									</td>
									<td>
										<DIV id="divSubsidiary" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px;FONT: 11px arial, verdana, sans-serif;" ></DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Business Description</strong></td>
								</tr>
								<tr>
									<td colspan="2"><DIV style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:60px; FONT: 11px arial, verdana, sans-serif;" id="divBusinessDescription"></DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Summary Financials</strong>
									</td>
								</tr>
								<tr>
									<td colspan="2">
										<DIV id="divSummaryFinancial" style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:220px; FONT: 11px arial, verdana, sans-serif;"></DIV>
									</td>
								</tr>
							</table>
							<!--  Company search ends -->						
						</div>
						<!--  tab 1 ends -->

						<!--  tab 2 starts -->
						<div id="divCustomizedReportTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
							
							<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
									id="tab4" width="750" height="800"
									codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
								<param name="movie" value="tab4.swf" />
								<param name="quality" value="high" />
								<param name="bgcolor" value="#ffffff" />
								<param name="allowScriptAccess" value="sameDomain" />
								<param name="flashVars" value="reportId=-1">
								<embed src="tab4.swf" quality="high" bgcolor="#ffffff"
									width="750" height="800" name="tab4" align="middle"
									play="true"
									loop="false"
									quality="high"
									allowScriptAccess="sameDomain"
									type="application/x-shockwave-flash"
									flashVars="reportId=-1"
									pluginspage="http://www.adobe.com/go/getflashplayer">
								</embed>
							</object>
							
						</div>
						<!--  tab 2 ends -->
						
						<!--  tab 3 starts -->
						<div id="divMailingListsTab" style="height:550px;MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
							<table style="padding: 20 0 20 0;width:100%">
								<tr>
									<td>
										<p/><input type="radio" name="radDirectorAddressType" id="directorType1" value="1"/><label for="directorType1">Director Home Address</label> 
										<p/><input type="radio" name="radDirectorAddressType" id="directorType2" value="2" checked="checked"><label for="directorType2">Registered Office Address</label> 
										<p/><input type="radio" name="radDirectorAddressType" id="directorType3" value="3"/><label for="directorType3">Trading Address</label>
									</td>
									<td>
										<select id="lstDirectorSections" size = 7" style="width:218px;FONT: 11px arial, verdana, sans-serif;">
										<%
											Map directorSections = BibServiceManager.getDirectorSections();
											for(Object key : directorSections.keySet()){
												out.println("<option value='" + key + "'>" + directorSections.get(key) + "</option>");
											}
										%>
										</select>
									</td>
									<td>
										<p>&nbsp;</p>
										<input type="button" value="Add Selection >" onclick="moveDirectorSectionRecord('lstDirectorSections','lstSelectedDirectorSections', false)" style ="FONT-SIZE: 11px; WIDTH: 105px"/><br/>
										<input type="button" value="< Remove Selection" onclick="moveDirectorSectionRecord('lstSelectedDirectorSections', 'lstDirectorSections', true)" style ="FONT-SIZE: 11px; WIDTH: 105px"/>
									</td>
									<td>
										<select id="lstSelectedDirectorSections" size = 7" style="width:218px;FONT: 11px arial, verdana, sans-serif;">
										</select>									
									</td>
								</tr>
							</table>
							<div width="100%" style="float: right;padding-right:10px;">
								<input type="button" value="Export Mailing List" style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="exportMailingList();"/>
							</div>								
						</div>
						<!--  tab 3 ends -->						

					</td>
				</tr>
				<tr>
					<td><jsp:include page="mr_footer.jsp"/></td>
				</tr>
			</table>
		</div>
		
		<script>
			//Start Tab Content script for UL with id="maintab" Separate multiple ids each with a comma.
			initializetabcontent("maintab");

			// Attach the event listener on the search reports textfield to respond to the Enter keypress.
			jQuery("#txtSearchReport").live("keydown",
				function(event){
				  	if(event.keyCode==13){
				  		searchReports();
				  	}
		  		}
		  	);

			// Attach the event listener on the search reports textfield to respond to the Enter keypress.
			jQuery("#txtSearchCompany").live("keydown",
				function(event){
				  	if(event.keyCode==13){
				  		searchCompaniesByKeyword();
				  	}
		  		}
		  	);
			
			//load the menu.
			createMenubar();			
		</script>
	</body>
</html>